package me.edzh.spring.bootstrap.interceptor;

import lombok.extern.log4j.Log4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Log4j
public class CORSInterceptor extends HandlerInterceptorAdapter {

    @Autowired(required = false)
    private CORSProvider corsProvider;


    public CORSInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (corsProvider != null) {
            var origin = request.getHeader("Origin");
            var origins = corsProvider.allowedOrigins();


            if (origins.contains(origin)) {
                response.setHeader("Access-Control-Allow-Origin", origin);
                response.setHeader("Vary", "Origin");
                response.setHeader("Access-Control-Allow-Methods", String.join(",", corsProvider.allowedMethods()));
                response.setHeader("Access-Control-Allow-Headers", String.join(",", corsProvider.allowedHeaders()));
                response.setHeader("Access-Control-Allow-Credentials", "true");
            }

            return true;

        }

        return super.preHandle(request, response, handler);
    }

    public interface CORSProvider {
        List<String> allowedOrigins();
        String[] allowedMethods();
        String[] allowedHeaders();
    }
}
